﻿namespace dogd
{
	using System;
	using System.Collections.Generic;

	/// <summary>
	/// Cache of sql statements used by repository to avoid regeneration of 
	/// sql every time.
	/// </summary>
	public class SqlStatementCache
	{
		private Dictionary<SqlCacheKey, string> sqlDictionary;

		/// <summary>
		/// Initialize default instance
		/// </summary>
		public SqlStatementCache()
		{
			this.sqlDictionary = new Dictionary<SqlCacheKey, string>();
		}

		/// <summary>
		/// Add a sql statement associated with a crud operation for a given type
		/// </summary>
		/// <param name="type"></param>
		/// <param name="sqlStatement"></param>
		/// <param name="option"></param>
		public void Add(Type type, string sqlStatement, CrudOption option)
		{
			this.sqlDictionary[new SqlCacheKey(type, option)] = sqlStatement;
		}

		/// <summary>
		/// Finds the sql statement corresponding to a type and a crud operation
		/// </summary>
		/// <param name="type"></param>
		/// <param name="option"></param>
		/// <returns></returns>
		public string Find(Type type, CrudOption option)
		{
			string found = string.Empty;

			this.sqlDictionary.TryGetValue(new SqlCacheKey(type, option), out found);

			return found;
		}

		private struct SqlCacheKey
		{
			public readonly Type InstanceType;
			public readonly CrudOption CrudCommand;

			public SqlCacheKey(Type type, CrudOption command)
			{
				this.InstanceType = type;
				this.CrudCommand = command;
			}
		}
	}
}
